package client

import (
	. "chess_platform/internal/common"
	"fmt"
	"time"
)

//游戏公告，公告(1-活动公告,2-系统公告)

//列出活动公告(1-活动公告,2-系统公告)
func ListActivityNotice() ([]*ActivityNotice, error) {
	var gl []*ActivityNotice
	err := GetCache(RedisCache, KeyNotice, &gl)
	if err != nil { //cache doesn't exist
		now := time.Now().Unix()
		where := fmt.Sprintf(` publish_time < %v AND expire_time > %v AND status = 0`, now, now)
		sql := fmt.Sprintf(`
		SELECT
			id,type,title,notice_url,detail_url,content,show_now,publish_time,expire_time
		FROM
			%v
		WHERE
			%v
		ORDER BY
			modify_time DESC
		`, TableActivityNotice, where)
		o := NewDBOrm(DBChessSysData)
		_, err := o.Raw(sql).QueryRows(&gl)
		status := CheckErrorStatus(err)
		if status == NoExist || status == InvalidConn {
			return gl, nil
		} else if status == ErrorHappen {
			return gl, err
		}
		//只有没有错的情况才存入缓存
		SetCache(RedisCache, KeyNotice, gl, CacheExpire) //one day
	}
	return gl, nil
}

//列出指定游戏招募代理公告,已做缓存
func ListAgentNotice(gameId int64) (*AgentNotice, error) {
	var gl AgentNotice
	Key := fmt.Sprintf("%v%v", KeyAgentNotice, gameId)
	err := GetCache(RedisCache, Key, &gl)
	if err != nil {
		sql := fmt.Sprintf(`
		SELECT
			content
		FROM
			%v
		WHERE
			game_id = ?
		LIMIT 1
		`, TableAgentNotice)
		o := NewDBOrm(DBChessSysData)
		err := o.Raw(sql, gameId).QueryRow(&gl)
		status := CheckErrorStatus(err)
		if status == NoExist || status == InvalidConn {
			return &gl, nil
		} else if status == ErrorHappen {
			return &gl, err
		}
		//只有没有错的情况才存入缓存
		SetCache(RedisCache, Key, gl, CacheExpire) //一天
	}
	return &gl, nil
}

//列出指定游戏活动公告,已做缓存
func ListGameNotice(gameId int64) ([]*GameNotice, error) {
	var gl []*GameNotice
	Key := fmt.Sprintf("%v%v", KeyGameNotice, gameId)
	err := GetCache(RedisCache, Key, &gl)
	if err != nil {
		now := time.Now().Unix()
		where := fmt.Sprintf(` publish_time < %v AND expire_time > %v AND status = 0`, now, now)
		sql := fmt.Sprintf(`
		SELECT
			title,content,notice_url,detail_url,publish_time,expire_time
		FROM
			%v
		WHERE
			game_id = ? AND %v
		ORDER BY
			modify_time DESC
		`, TableGameNotice, where)
		o := NewDBOrm(DBChessSysData)
		_, err := o.Raw(sql, gameId).QueryRows(&gl)
		status := CheckErrorStatus(err)
		if status == NoExist || status == InvalidConn {
			return gl, nil
		} else if status == ErrorHappen {
			return gl, err
		}
		//只有没有错的情况才存入缓存
		SetCache(RedisCache, Key, gl, CacheExpire) //one day
	}
	return gl, nil
}
